<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" destroyOnClose showFooter :title="title" :width="drawerWidth" @ok="handleSubmit">
    <Description size="middle" class="mt-4" title="基础信息" :column="{ xxl: 4, xl: 3, lg: 3, md: 3, sm: 2, xs: 1 }" :data="backcardDetailInfo.data" :schema="commonInfoSchema" />
    <BasicForm @register="registerForm">
      <template #vipBearAmountTip="{ model, field }"
        ><p style="color: red">
          请填写会员实际承担金额，系统将自动计算并生成对应退款金额
        </p></template
      >
      <template #refundWayTip="{ model, field }"
        ><p style="color: red">
          原路退回方式则会直接线上退回，请仔细核对退款金额,避免退错金额
        </p></template
      >
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" setup>
import { reactive, ref, unref } from 'vue';
import { BasicForm, FormSchema, useForm } from '@apps/antd-admin/src/components/Form/index';
import { BasicDrawer, useDrawerInner } from '@apps/antd-admin/src/components/drawer';
import { commonInfoSchema, formSchema10, formSchema11, formSchema6, formSchema8, formSchema9 } from '../data/data';
import { Api, getBackcardRecordDetail } from '../data/api';
import { useAppInject } from '@apps/antd-admin/src/hooks/web/use-app-inject';
import { useMessage } from '@apps/antd-admin/src/hooks/web/useMessage';
import { Description } from '@apps/antd-admin/src/components/description';

const { createMessage, createConfirm } = useMessage();
const { getIsMobile } = useAppInject();
const drawerWidth = ref('1000px');
if (unref(getIsMobile)) {
  drawerWidth.value = '70%';
}
// 声明Emits
const emit = defineEmits(['success', 'register']);
//是否是编辑模式
const isUpdate = ref(true);

let backcardDetailInfo: Recordable = reactive({ data: {} });

const formSchemaRef: any = ref<FormSchema[]>([]); // 改用 ref 引用

//配置表单
const [registerForm, { resetFields, updateSchema, resetSchema, setFieldsValue, validate, saveOrUpdate }] = useForm({
  rowKey: 'backcardRecordId',
  saveApi: Api.add,
  updateApi: Api.updateBackCardRecord,
  schemas: formSchemaRef,
  labelCol: { span: 7 },
});

//表单赋值
const title = ref('');
const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async data => {
  setDrawerProps({ confirmLoading: false });
  await resetFields();
  isUpdate.value = !!data?.isUpdate;
  title.value = data.title;
  let isCheck = data.isCheck;
  if (isUpdate.value) {
    let backcardRecordId = data.record.backcardRecordId;
    let queryResult = await getBackcardRecordDetail({
      backcardRecordId: backcardRecordId,
      handlerName: 'busBackcardDetailHandler',
    });
    if (queryResult.canRefundOriginal) {
      queryResult.canRefundOriginal = 1;
    } else {
      queryResult.canRefundOriginal = 2;
    }
    backcardDetailInfo.data = queryResult;
    backcardDetailInfo.data = queryResult;
    let payAmount = queryResult.payAmount;
    if (queryResult.isUpgrade == 1) {
      payAmount = queryResult.upgradePayAmount;
    }
    console.info('isCheck', isCheck);
    const schemaMap = {
      6: formSchema6,
      8: formSchema8,
      9: formSchema9,
      10: formSchema10,
      11: formSchema11,
    };
    if (schemaMap[isCheck]) {
      formSchemaRef.value = schemaMap[isCheck];
      resetSchema(formSchemaRef.value);
    }
    //需要补退的
    if (isCheck == 10) {
      queryResult['addRefundWay'] = '';
      queryResult['addRefundAmount'] = '';
      queryResult['addRefundRemark'] = '';
      queryResult['maxAddRefundAmount'] = Number((Number(payAmount) - Number(queryResult.refundAmount)).toFixed(2));
    }
    let result = Object.assign({}, queryResult, { isCheck: isCheck, payAmount: payAmount });
    setFieldsValue(result);
  }
});

/**
 * 表单提交
 */
async function handleSubmit() {
  try {
    const values = await validate();
    if ((values.isCheck == 9 || values.isCheck == 10) && values.refundWay == 'refund_original') {
      createConfirm({
        iconType: 'warning',
        title: '如果原支付方式为线上支付,选择原路退回方式则会直接线上退回，请仔细核对退款金额',
        content: '选择原路退回方式则会直接线上退回，请仔细核对退款金额,避免退错金额，是否退款？',
        onOk: async () => {
          setDrawerProps({ confirmLoading: true });
          await saveOrUpdate(emit);
          closeDrawer();
        },
        onCancel: async () => {
          closeDrawer();
        },
      });
    } else {
      setDrawerProps({ confirmLoading: true });
      await saveOrUpdate(emit);
      closeDrawer();
    }
  } finally {
    setDrawerProps({ confirmLoading: false });
  }
}
</script>
